<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue'

import Web3 from 'web3'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const password = ref('')
const wallet = reactive(JSON.parse(localStorage.getItem('wallet') as string) || {})
const keystore = wallet.keystore
const web3 = new Web3(
  Web3.givenProvider || 'https://sepolia.infura.io/v3/88b2bd48430847fab3c22b93a7c07d69'
)
const visiable = ref(localStorage.getItem('hasLogin') != null)
const doLogin = async () => {
  // const t = await web3.eth.accounts.decrypt(keystore, password.value)
  // console.log('密码', t)
  const newwallet = ref()
  if (wallet == null || keystore == null) {
    return
  }

  try {
    newwallet.value = await web3.eth.accounts.decrypt(wallet.keystore, password.value)
    localStorage.setItem('hasLogin', 'true')
    ElMessage({
      message: '登录成功',
      type: 'success'
    })
  } catch (error) {
    ElMessage({
      message: '密码错误',
      type: 'error'
    })
    return false
  }
  await router.push({
    path: '/user/mask/info'
  })
}

watchEffect(() => {
  console.log('login',wallet.keystore)
  console.log('login',visiable.value)
  if (visiable.value === true ) {
    router.push({
      path: '/user/mask/info'
    })
  }else if(wallet.keystore==undefined)
  {
    router.push({
      path:"/user/maskIndex"
    })
  }
    // else {
  //   router.push({
  //     path: '/user/maskIndex'
  //   })
  // }
})
</script>

<template>
  <div id="maskLogin">
    <el-card class="box-card" body-style="weight:713px" shadow="always">
      <template #header>
        <div class="card-header">
          <h2 style="text-align: center">账户登录</h2>
          <h3 style="text-align: center">欢迎回来！即将进入去中化网络！！！</h3>
        </div>
        <el-space style="height: 150px">
          <div class="avatar">
            <el-avatar size="large" src="http://s9ngh6vu2.hn-bkt.clouddn.com/logo2.png" />
          </div>
        </el-space>
      </template>

      <template #default>
        <div class="text item">
          <el-input type="password" v-model="password"></el-input>
        </div>
      </template>

      <template #footer>
        <div class="button">
          <el-button type="primary" style="width: 150px" @click="doLogin">登录</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.el-avatar--large {
  --el-avatar-size: 125px;
}

.box-card {
  height: 600px;
  width: 100%;
}

.avatar {
  height: 150px;

  position: absolute;
  left: 55%;
  top: 25%;
}

.button {
  position: absolute;
  left: 55%;
  top: 70%;
}
</style>
